package com.practice.mybatis.v2.statement;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.practice.mybatis.v2.config.Configuration;
import com.practice.mybatis.v2.config.MapperRegistory.MapperData;
import com.practice.mybatis.v2.result.ResultHandler;

public class StatementHandler {
	
	private Configuration configuration;
	
	private ResultHandler resultHandler;

	public StatementHandler(Configuration configuration) {
		this.configuration = configuration;
		resultHandler = new ResultHandler(configuration);
	}

	public <E> E query(MapperData<E> mapperData, Object parameter) {
		Connection conn = this.getConnection();
		PreparedStatement ps;
		try {
			ps = conn.prepareStatement(String.format(mapperData.getSql(),
			        Integer.valueOf(String.valueOf(parameter))));
			ps.execute();
			return (E) resultHandler.handler(ps.getResultSet(), mapperData.getType());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	private Connection getConnection() {
		String driver = "oracle.jdbc.OracleDriver";
        String url = "jdbc:oracle:thin:@133.96.46.110:1521:daasan";
        String username = "cgtax_v_311_ts_20180906";
        String password = "cgtax_db";
        Connection conn = null;
        try {
            Class.forName(driver); //classLoader,加载对应驱动
            conn = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
	}

}
